<template>
  <div class="experiences-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white">
              特色体验
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              探索贵港独特的文化体验活动
            </p>
          </div>
          <el-button
            class="back-btn"
            type="primary"
            plain
            @click="router.push('/')"
          >
            <el-icon class="mr-1"><Back /></el-icon>
            返回首页
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="flex flex-col lg:flex-row gap-8">
        <!-- 左侧主要内容区 -->
        <div class="flex-1">
          <!-- 搜索和筛选区 -->
          <div
            class="search-filter-section bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-8"
          >
            <!-- 搜索框 -->
            <div class="search-box mb-6">
              <el-input
                v-model="searchQuery"
                placeholder="搜索体验活动"
                class="search-input"
                clearable
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>

            <!-- 筛选条件 -->
            <div class="filter-conditions flex items-center gap-4">
              <!-- 分类筛选 -->
              <el-select
                v-model="filterConditions.category"
                placeholder="活动分类"
                clearable
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>

              <!-- 价格筛选 -->
              <el-select
                v-model="filterConditions.priceRange"
                placeholder="价格区间"
                clearable
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="price in priceRanges"
                  :key="price.value"
                  :label="price.label"
                  :value="price.value"
                />
              </el-select>

              <!-- 排序方式 -->
              <el-select
                v-model="filterConditions.sortBy"
                placeholder="排序方式"
                class="!w-[140px]"
                @change="handleFilter"
              >
                <el-option
                  v-for="sort in sortOptions"
                  :key="sort.value"
                  :label="sort.label"
                  :value="sort.value"
                />
              </el-select>
            </div>
          </div>

          <!-- 体验列表 -->
          <div
            class="experiences-list grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
            v-loading="loading"
          >
            <div
              v-for="exp in experiencesList"
              :key="exp.id"
              class="experience-card bg-white dark:bg-gray-800 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-all duration-300 cursor-pointer"
              @click="handleExperienceClick(exp)"
            >
              <div class="relative">
                <el-image
                  :src="exp.image"
                  class="w-full aspect-[16/9] object-cover transition-transform duration-300 hover:scale-105"
                  fit="cover"
                >
                  <template #placeholder>
                    <div class="image-placeholder">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
                <div class="absolute top-4 left-4 flex gap-2">
                  <el-tag
                    :type="exp.status === 'booking' ? 'success' : 'warning'"
                    effect="light"
                  >
                    {{ exp.status === "booking" ? "可预订" : "名额告罄" }}
                  </el-tag>
                  <el-tag v-if="exp.isHot" type="danger" effect="light"
                    >热门</el-tag
                  >
                </div>
                <div class="absolute top-4 right-4">
                  <el-button
                    circle
                    :class="{ 'is-favorite': exp.isFavorite }"
                    @click.stop="toggleFavorite(exp)"
                  >
                    <el-icon><Star /></el-icon>
                  </el-button>
                </div>
              </div>
              <div class="p-4">
                <h3
                  class="text-lg font-medium text-gray-900 dark:text-white mb-2 line-clamp-1"
                >
                  {{ exp.title }}
                </h3>
                <p
                  class="text-gray-600 dark:text-gray-400 text-sm mb-4 line-clamp-2"
                >
                  {{ exp.description }}
                </p>
                <div class="flex items-center justify-between">
                  <div class="flex items-center">
                    <el-avatar :size="24" :src="exp.host.avatar" class="mr-2" />
                    <span class="text-sm text-gray-500 dark:text-gray-400">{{
                      exp.host.name
                    }}</span>
                  </div>
                  <div
                    class="text-primary-600 dark:text-primary-400 font-medium"
                  >
                    ¥{{ exp.price }}起
                  </div>
                </div>
                <div
                  class="mt-4 flex items-center justify-between text-sm text-gray-500 dark:text-gray-400"
                >
                  <div class="flex items-center gap-4">
                    <span class="flex items-center">
                      <el-icon class="mr-1"><Timer /></el-icon>
                      {{ exp.duration }}
                    </span>
                    <span class="flex items-center">
                      <el-icon class="mr-1"><User /></el-icon>
                      {{ exp.maxParticipants }}人
                    </span>
                  </div>
                  <el-rate
                    v-model="exp.rating"
                    disabled
                    :max="5"
                    class="scale-75 -mr-2"
                  />
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <el-empty
              v-if="!loading && !experiencesList.length"
              description="暂无相关体验活动"
            >
              <el-button type="primary" @click="resetFilters"
                >清除筛选</el-button
              >
            </el-empty>
          </div>

          <!-- 分页 -->
          <div
            v-if="total > 0"
            class="pagination-wrapper flex justify-center mt-8"
          >
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[12, 24, 36, 48]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 右侧边栏 -->
        <div class="sidebar lg:w-80 flex-shrink-0">
          <!-- 热门体验 -->
          <div
            class="hot-experiences bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Star /></el-icon>
              热门体验
            </h3>
            <div class="hot-experiences-list space-y-4">
              <div
                v-for="exp in hotExperiences"
                :key="exp.id"
                class="hot-experience-item group cursor-pointer"
                @click="handleExperienceClick(exp)"
              >
                <div class="relative rounded-lg overflow-hidden mb-2">
                  <el-image
                    :src="exp.image"
                    class="w-full h-32 object-cover group-hover:scale-105 transition-transform duration-300"
                  />
                  <div
                    class="absolute inset-0 bg-black/30 group-hover:bg-black/10 transition-colors"
                  ></div>
                </div>
                <h4
                  class="text-sm font-medium text-gray-900 dark:text-white group-hover:text-primary-600 dark:group-hover:text-primary-400 line-clamp-2 mb-2 transition-colors"
                >
                  {{ exp.title }}
                </h4>
                <div
                  class="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400"
                >
                  <span class="text-primary-600 dark:text-primary-400"
                    >¥{{ exp.price }}起</span
                  >
                  <span class="flex items-center">
                    <el-icon class="mr-1"><User /></el-icon>
                    已有{{ formatNumber(exp.participants) }}人参与
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 体验分类 -->
          <div
            class="experience-categories bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
          >
            <h3
              class="text-lg font-medium text-gray-900 dark:text-white mb-4 flex items-center"
            >
              <el-icon class="mr-2"><Menu /></el-icon>
              体验分类
            </h3>
            <div class="categories-list space-y-2">
              <div
                v-for="category in categories"
                :key="category.value"
                class="category-item flex items-center justify-between p-2 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg transition-all duration-300"
                @click="handleCategoryClick(category)"
              >
                <span class="text-gray-700 dark:text-gray-300">{{
                  category.label
                }}</span>
                <el-tag size="small" :type="category.type" effect="light">{{
                  category.count
                }}</el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import {
  Search,
  Back,
  Star,
  Picture,
  Timer,
  User,
  Menu,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import service from "@/api/axios";

const router = useRouter();
const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

// 筛选条件
const filterConditions = reactive({
  category: "",
  priceRange: "",
  sortBy: "recommended",
});

// 分类数据
const categories = ref([
  { label: "手工艺", value: "craft", type: "", count: 28 },
  { label: "非遗文化", value: "heritage", type: "info", count: 15 },
  { label: "美食制作", value: "cooking", type: "success", count: 32 },
  { label: "农事体验", value: "farming", type: "warning", count: 18 },
  { label: "文化表演", value: "performance", type: "danger", count: 24 },
]);

// 价格区间
const priceRanges = [
  { label: "50元以下", value: "0-50" },
  { label: "50-100元", value: "50-100" },
  { label: "100-200元", value: "100-200" },
  { label: "200元以上", value: "200-up" },
];

// 排序选项
const sortOptions = [
  { label: "推荐排序", value: "recommended" },
  { label: "最新发布", value: "newest" },
  { label: "价格从低到高", value: "price-asc" },
  { label: "价格从高到低", value: "price-desc" },
  { label: "评分最高", value: "rating-desc" },
];

// 体验列表数据（默认测试数据）
const experiencesList = ref([
  {
    id: 1,
    title: "贵港陶艺制作体验",
    description: "跟随陶艺大师学习传统陶艺技艺，创作专属作品",
    image: "/images/experiences/pottery.jpg",
    status: "booking",
    price: 128,
    duration: "2小时",
    maxParticipants: 10,
    rating: 4.8,
    isHot: true,
    isFavorite: false,
    host: {
      name: "张师傅",
      avatar: "/images/avatars/host1.jpg",
    },
  },
  // 更多体验数据...
]);

// 热门体验数据（默认测试数据）
const hotExperiences = ref([
  {
    id: 1,
    title: "非遗扎染工艺体验",
    image: "/images/experiences/dyeing.jpg",
    price: 168,
    participants: 1280,
  },
  // 更多热门体验...
]);

// 获取体验列表
const getExperiencesList = async () => {
  loading.value = true;
  try {
    // 构建API参数（移除分页参数）
    const params = {
      search: searchQuery.value || undefined,
      category: filterConditions.category || undefined,
      priceRange: filterConditions.priceRange || undefined,
      sortBy: filterConditions.sortBy || 'recommended'
    };
    
    // 调用获取体验列表API
    const response = await service.get('/public/experiences', { params });
    
    if (response && response.data && Array.isArray(response.data)) {
      // 存储完整数据用于前端分页
      const allExperiences = response.data;
      total.value = allExperiences.length;
      
      // 前端分页处理
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      experiencesList.value = allExperiences.slice(startIndex, endIndex);
    } else {
      // 如果API没有返回数据，使用测试数据
      total.value = experiencesList.value.length;
    }
  } catch (error) {
    console.error("获取体验列表失败:", error);
    ElMessage.error("获取体验列表失败");
    // 出错时使用测试数据
  } finally {
    loading.value = false;
  }
};

// 获取热门体验
const getHotExperiences = async () => {
  try {
    // 调用获取热门体验API
    const response = await service.get('/public/experiences/hot');
    
    if (response && response.data && Array.isArray(response.data)) {
      hotExperiences.value = response.data;
    }
    // 如果API没有返回数据，保留测试数据
  } catch (error) {
    console.error("获取热门体验失败:", error);
    // 出错时保持测试数据不变
  }
};

// 获取分类数据
const getCategories = async () => {
  try {
    // 调用获取分类API
    const response = await service.get('/public/experiences/categories');
    
    if (response && response.data && Array.isArray(response.data)) {
      categories.value = response.data;
    }
    // 如果API没有返回数据，保留测试数据
  } catch (error) {
    console.error("获取分类数据失败:", error);
    // 出错时保持测试数据不变
  }
};

// 格式化数字
const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num);
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getExperiencesList();
};

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1;
  getExperiencesList();
};

// 重置筛选
const resetFilters = () => {
  searchQuery.value = "";
  Object.assign(filterConditions, {
    category: "",
    priceRange: "",
    sortBy: "recommended",
  });
  currentPage.value = 1;
  getExperiencesList();
};

// 处理体验点击
const handleExperienceClick = (exp) => {
  router.push(`/experiences/${exp.id}`);
};

// 处理收藏
const toggleFavorite = async (exp) => {
  try {
    // 调用收藏API
    const isCurrentlyFavorite = exp.isFavorite;
    const endpoint = `/experiences/favorite/${exp.id}`;
    const method = isCurrentlyFavorite ? 'delete' : 'post';
    
    await service[method](endpoint);
    
    // 更新本地状态
    exp.isFavorite = !isCurrentlyFavorite;
    ElMessage.success(exp.isFavorite ? "收藏成功" : "已取消收藏");
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("收藏操作失败，请确保已登录");
  }
};

// 处理分类点击
const handleCategoryClick = (category) => {
  filterConditions.category = category.value;
  currentPage.value = 1;
  getExperiencesList();
};

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  getExperiencesList();
};

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getExperiencesList();
};

// 页面加载时获取数据
onMounted(() => {
  getExperiencesList();
  getHotExperiences();
  getCategories();
});
</script>

<style lang="scss" scoped>
.experiences-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .image-placeholder {
    @apply flex items-center justify-center w-full h-full bg-gray-100 dark:bg-gray-700;
    .el-icon {
      @apply text-4xl text-gray-400 dark:text-gray-500;
    }
  }

  .experience-card {
    .is-favorite {
      @apply text-red-500;
    }
  }

  :deep(.el-rate) {
    .el-rate__icon {
      &.el-icon {
        @apply text-yellow-400 dark:text-yellow-500;
      }
    }
  }
}
</style>
